package com.tomato.lock.common;

import com.tomato.lock.util.TomatoThreadPoolUtil;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.tomato.lock.util.TomatoThreadPoolUtil.*;
import static java.text.MessageFormat.format;

/**
 * lock接口获取的锁，如果程序发生异常并不会手动释放锁
 * 因此在写程序过程中有，程序最后一定要释放锁，规范如下：
 * <pre>
 *     try {
 *         lock.lock();
 *     } finally {
 *         lock.unlock();
 *     }
 * </pre>
 */
public class LockAndUnlockTest {

    // 创建锁对象，锁对象最好是声明为static
    public static Lock lock = new ReentrantLock();

    public static void task() {
        // 获取锁
        lock.lock();
        try {
            // 执行任务时休眠1s，注意休眠时不会释放锁
            Thread.sleep(1_000);
            // 输出语句
            System.out.println(format("{0}开始执行任务", Thread.currentThread().getName()));
        } catch (InterruptedException e) {

        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i <= 5; i++) {
            // 执行任务
            THREAD_POOL.execute(LockAndUnlockTest::task);
        }
    }
}
